<?php
/**
 * Description of CommonAction.class
 * 通用操作，页头、页尾、用户登录注销、激活、忘记密码等
 */

class CommonAction extends Action {

	/* 缓存时间半小时
	 *
	 */
	const EBC_CACHETIME = 1800;

    /** 初始化操作
     */
    protected function _initialize() {
        C(include APP_PATH.'/../Admin/Runtime/Data/~config.php');
        if (!empty($_SESSION[C('USER_AUTH_KEY')])) {
            $this->assign('userAuthMark', 1);
        }
		//系统默认设置
		$this->assign("detitle",C("HOME_TITLE"));
		$this->assign("dekeywords",C('DEFAULT_KEYWORDS'));
		$this->assign("titleSuffix",C("TITLE_SUFFIX"));
		$this->assign("description",C("DEFAULT_DESCRIPTION"));
                $this->assign("districtmenu",C("district"));
                $this->assign("layoutmenu",C("layout"));
    }

    /** 页头
     */
    public function top() {
        $this->assign('menu', $this->menu()); // 生成导航菜单
    }

    /** 顶部搜索+菜单显示
     */
    public function menu() {
    }

    /** 左边产品菜单
     */
    public function menuLeft() {
		$model = D('Product');
        $cateList =S("SavePCate");
        if(empty($cateList)) {
			$productCate =D('Productcate');
			$cateList = $productCate->getChildCates();//默认系统分类
			foreach ($cateList as $k => $v) {
				$cateList[$k]['count'] = $model->getProCount($v['id']);
				foreach ($v['_child'] as $m => $n) {
					$cateList[$k]['_child'][$m]['count'] = $model->getProCount($n['id']);
				}
			}
            S("SavePCate",$cateList, self::EBC_CACHETIME);
        }
		
        $this->assign("cateList",$cateList);
        return $this->fetch("Index:menuLeft");
    }

    /** 合作伙伴显示
     */
    public function cooperation() {
        return $this->fetch("Index:cooperation");
    }

    /** 报错页面
     *
     */
    public function error($message,$ajax=false,$sec=10) {
		//META
		$this->assign('title', '发生错误啦或您需要重新登录！');
		$this->assign('seconds', $sec);
        parent::error($message,$ajax=false);
    }

    /** 成功页面
     *
     */
    public function success($message,$ajax=false,$sec=5) {
		$this->assign('title', '操作成功！');
		$this->assign('seconds', $sec);
        parent::success($message,$ajax=false);
    }

	/** 注册
	 */
	public function register() {
		if(!empty($_POST['account'])) { //如果提交了表单，进行注册处理
			if ($_SESSION['verify'] != md5($_POST['verify'])) {
				$this->assign('jumpUrl', __ACTION__.'/');
				$this->error("验证码有误！");
			}
			// 检查email是否合法
			if (false === chkemail($_POST['email'])) {
				$this->assign('jumpUrl', __ACTION__);
				$this->error("邮箱填写不正确，请重新填写！");
			}
                        elseif(empty($_POST['name'])) {
                            $this->error("请填写真实姓名！");
                        }
			$Member = D('Member');
                        $data = $_POST;
                        $data['password'] = md5($_POST['password']);
                        $data['status'] = 1;
                        $data['create_time'] = time();
                        //TODO 记录客户来源，入住分店，
                        if(false == $Member -> create() ){
                            $this->assign('jumpUrl', __ACTION__);
                            $this->error($Member->getError());
                        };
                        if(false != $stat = $Member->add($data) ){
                            $this->assign('jumpUrl', __APP__.'/Member/');
                            $msg = "好家服务公寓有新会员注册，姓名：".$_POST['name'].",邮箱：".$_POST['email'].',手机：'.$_POST['mobile'];
                            //短信通知系统人员
                            //sendMsg($msg);
                            //发邮件通知
                            $alert_value = M('Configure')->where('var_name = "alert_type" ')->getField('value');
                            if ($alert_value == 1) {
                                sendMail("上海好家服务公寓提醒信息", $msg, "上海好家服务公寓<info@okhome.cn>", 'lm@okhome.cn');
                            }
                            
                            $this->assign('user',$_POST['name']);
                            $this->assign('account',$_POST['account']);
                            $this->assign('password',$_POST['password']);
                            $content = $this->fetch('Email:new_member');
                            sendMail("上海好家服务公寓帐号信息", $content,"上海好家服务公寓<info@okhome.cn>", $_POST['email']);
                            $this->success("恭喜您，成为上海好家公寓会员！");
                        }
			else {
				$this->error($stat);
			}
		}
		else {
			$this->display();
		}
	}

    /** 登录验证
     */
    public function checkLogin() {
        if(empty($_POST['account']) || empty($_POST['password'])) {
            $this->error('请输入用户名或密码');
        }
        //生成认证条件
        $map = array();
        $map["account"] = $_POST['account'];
        //$map["account"] = $_POST['account'];
        $map["status"] = array('egt', 0);
        $model = D('Member');
        $authInfo = $model->where($map)->find();
        //使用用户名、密码和状态的方式进行认证
        if (preg_match('/^[0-9]+$/', $authInfo['id'])) {
            if ($authInfo['password'] != md5($_POST['password'])) {
                $this->error("用户名或密码错误！");  // 密码不正确
            }
            $_SESSION[C('USER_AUTH_KEY')] = $authInfo['id'];
            $_SESSION['MemberName'] = $authInfo['name'];
            if (empty($_COOKIE['returnUrl'])) {
                $this->assign('jumpUrl', __APP__.'/Member');
            }
            else {
                $this->assign('jumpUrl',$_COOKIE['returnUrl']);
                setcookie("returnUrl",'' ,time()-31536000,'/', $_SERVER['SERVER_NAME']);
            }
            $this->success("欢迎您！".$authInfo['name']);
        }
        else {
            $this->error("用户不存在，请重新输入或注册成为新会员！"); // 用户不可用
        }
    }

    /** 登录页面显示
     */
    public function login() {
        if (!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->display();
        }
        else {
            if (empty($_COOKIE['_returnUrl_'])) {
                $this->redirect(__APP__.'/');
            }
            else {
                $this->redirect($_COOKIE['_returnUrl_']);
            }
        }
    }

    /** 注销
     */
    public function logout() {
        if (isset($_SESSION[C('USER_AUTH_KEY')])) {
            unset($_SESSION[C('USER_AUTH_KEY')]);
            unset($_SESSION['MemberName']);
            $this->assign('jumpUrl', __APP__.'/');
            $this->success("您已安全退出！");
        }
        else {
            $this->assign('jumpUrl', __APP__.'/');
            $this->error("您已经退出系统了！");
        }
    }

    public function findPw() {
        if($_POST['email']) {
            if ($_SESSION['verify'] != md5($_POST['verify'])) {
                $this->error("验证码错误");
            }
            $member = M('Member');
            if(false == $result = $member ->where('email ="'.$_POST['email'].'"' )->find() ){
                $this->error("很抱歉，您暂未使用该邮箱注册！");
            }
            $pwd = rand_string(6,1);//6位数字
            $this->assign('email', $_POST['email']);
            $this->assign('password', $pwd);
            $this->assign('account', $result['account']);
            $this->assign('user', $result['name']);
            $map = array(
                    'email' => $_POST['email'],
            );
            $status = $member->where($map)->setField('password',md5($pwd) );
            if($status == true) {
                $content = $this->fetch('Email:repwd');
                sendMail('好家服务公寓密码重置信息', $content, '上海好家服务公寓<info@okhome.cn>', $_POST['email']);
                $this->assign('jumpUrl', __APP__.'/');
                $this->success("密码信息已经发送到您的邮箱:".$_POST['email']."请注意查收！", false, 10);
            }
            else {
                $this->error("密码重置失败，请重新操作。");
            }
        }
        else {//
            $this->display();
        }

    }

    /** 密码找回TODO
     */
        /*
    public function findPw() {
        if($_POST['email']) { // 开始重置流程
            if ($_SESSION['verify'] != md5($_POST['verify'])) {
                $this->error("验证码错误");
            }

			// 验证用户名
            $model = D('Webuser');
            $cond = array(
                    'email' => $_POST['email'],
            );
            $vo = $model->where($cond)->find();
            if ($vo['id']) {
                if ($vo['status'] > 0) { // 激活用户找回密码
                    // 生成fcode参数 id+account+time()
                    $fcode = unpack("H*", pp_encrypt($vo['id'] . ':' . $vo['email'] . ':' . time()));
					$url = 'http://' . $_SERVER['SERVER_NAME'] . __ACTION__ . '?reset=password&fcode=' . $fcode[1];
					// 发邮件
					$this->assign('url', $url);
					$this->assign('email', $vo['email']);
					$content = $this->fetch('Email:account_reset');
					multiSendMail('eBioChem.com password reset', $content, 'eBioChem.com <ebcadmin@ebiochem.com>', $vo['email']);
					$this->assign('jumpUrl', __APP__.'/');
					$this->success(L('check_mailbox'), false, 10);
				}
                else {  // 重新激活
                    $verifyString = rand_string();
                    $model->where('id='.$vo['id'])->setField('verify', $verifyString);
                    $code = unpack("H*", pp_encrypt($vo['id'].":".$verifyString));
                    $url ='http://'.$_SERVER["SERVER_NAME"].__URL__.'/memberActivate/activecode/'.$code[1];
                    $this->assign('url',$url);
                    $this->assign('email', $_POST['email']);
                    $content = $this->fetch('Email:account_active');
                    multiSendMail('eBioChem.com User Activation Link', $content, 'eBioChem.com <ebcadmin@ebiochem.com>', $_POST['email']);
                    $this->assign('jumpUrl', __APP__.'/');
                    $this->success(L('check_mailbox'), false, 10);
                }
            }
            else {
                $this->assign('jumpUrl', __APP__.'/');
                $this->error(L('op_error'));
            }
			exit;
        }
        if ($_POST['fcode']) {  // 开始重置密码
            // 验证fcode
            list($id,$name,$time) = split(':', pp_decrypt(pack("H*", $_POST['fcode'])));
            // 重置密码
            $model = D('Webuser');
            if ($time >= time() - 86400) { // 24小时内的重置
                if ($_POST['password'] != $_POST['repassword']) {
                    $this->error(L('password_unmatch'));
                }
                if (empty($_POST['password'])) {
                    $this->error(L('password_empty'));
                }
                $model->passwd = md5($_POST['password']);
                $model->id = $id;
                if ($model->save()) {
                    $this->assign('jumpUrl', __URL__.'/login/');
                    $this->success('['.$name.'] '.L('op_success'));
                }
                else {
                    $this->assign('jumpUrl', __URL__.'/login/');
                    $this->error(L('op_error'));
                }
            }
            else {
                $this->assign('jumpUrl', __URL__.'/login/');
                $this->error(L('op_error'));
            }
        }
        if(empty($_GET['fcode'])) {  // 开始重置页面显示
            $this->assign('new', 1);
            $this->display();
        }
        else {  // 密码重置页面显示
            list($id,$name,$time) = split(':', pp_decrypt(pack("H*", $_GET['fcode'])));
            if ($time >= time()-24*60*60) {
                $this->assign('set', 1);
                $this->assign('username', $name);
                $this->assign('fcode', $_GET['fcode']);
                $this->top();
                $this->footer();
                $this->display();
            }
            else {
                $this->assign('jumpUrl', __URL__.'/login');
                $this->error(L('op_error'));
            }
        }
    }
    */

    /** 验证码显示
     */
    public function verify() {
        import ('@.ORG.Util.Image');
        Image::buildImageVerify();
    }

       /**
     * 咨询
     */
    public function ask(){

        $member = $_SESSION[C('USER_AUTH_KEY')];
        if(!isset($member)){
            setcookie("returnUrl",$_SERVER['PHP_SELF'],0,'/');
            $this->assign('jumpUrl', __APP__.'/Index/login/');
            $this->error('请先登录！',false,3);
        }
        if(empty ($_POST['content'])){
             $this->display();
        }
        else {
            $data = $_POST;
            $data['member_id'] = $_SESSION[C('USER_AUTH_KEY')];
            $model = $_POST['type'] ==0 ? 'House':'Hotel'; //注意，类型及PID均为get
            //$data['title'] = "咨询:".getModelName($_POST['pid'], $model);
            $data['create_time'] = time();
            $data['parent'] = empty($_REQUEST['parent'])?0:$_REQUEST['parent'];
            $data['approved'] = 1;//默认为未处理
            $data['status'] = 0;//默认为禁止发表,需等待审核
            $Comment = D('Comment');
            if(false == $stat = $Comment->create()) {
                $this ->error($Comment->getError);
            }
            if(0 != $askId = $Comment->add($data)) {
                if(empty($_POST['pid'])){
                    $jumpUrl = '__APP__/Member/index/entry/message';
                }else{
                    $jumpUrl = __APP__.'/'.$model.'/index/id/'.$_POST['pid'];
                }
                $this -> assign('jumpUrl',$jumpUrl);
                $msg = '上海好家服务公寓有新留言,姓名：'.getModelName($data['member_id'], 'Member').',咨询：'.$data['content'];
                //sendMsg($msg);
                $alert_value = M('Configure')->where('var_name = "alert_type" ')->getField('value');
                if ( $alert_value == 1) {
                    //sendMail($subject, $content, '上海好家服务公寓<info@okhome.cn>', $email);
                    sendMail('上海好家服务公寓提醒信息', $msg, '上海好家服务公寓<info@okhome.cn>', 'lm@okhome.cn');
                }
                $this->success('非常感谢，您的留言已经成功提交！我们将尽快与您联系！',false,10);
            }
            else {
                $this ->error('对不起，留言出现问题啦，请重新留言或联系我们！');
            }
        }
    }

    /* 根据国家获取省份 TODO通过jQuery geonames.org自动获取国家地区信息，方便用户输入
	 *
    */
    public function getProvince() {
        $nation_id = intval($_POST["nation_id"]);
        $str = "<option value='-1'>-state/province-</option>";
        foreach(M("Province")->where("nation_id={$nation_id}")->order("indexno DESC")->select() as $value) {
            $str .= "<option value='{$value[id]}' title='{$value['ename']}'>{$value['ename']}</option>";
        }
        echo $str;
    }

    /*  根据省份获取城市
	 *
    */
    public function getCity() {
        $province_id = intval($_POST["province_id"]);
        $str = "<option value='-1'>--- city ---</option>";
        foreach(M("City")->where("province_id={$province_id}")->order("indexno DESC")->select() as $value) {
            $str .= "<option value='{$value[id]}' title='{$value['ename']}'>{$value['ename']}</option>";
        }
        echo $str;
    }

	/**
	 *获取邮件模板
	 * @param <type> $name 模板名称
	 * @param <type> $valName 模板变量名
	 * @param array $val 要传入模板中的数组变量
	 * @return <type>
	 */
	public function fetchMailTpl($name, $valName,array $val) {
		$this->assign($valName, $val);
		return $this->fetch('Email:'.$name);
	}

        /**
         * 获得产品的图片（logo及附属图片）
         * @param <type> $product_id 产品ID
         * @param <string> $objType 是公寓还是房型，直接传string
         * @param <type> $type 1=附属图片，2=logo
         * @return <type> 
         */
        public function get_picture($product_id,$objType,$type=1) {
            $condition[$objType.'_id']=$product_id;
            if(0!=$type) {
                $condition['attachfunc']=($type==1)?1:2;
            }
            $data = M("Attach")->field('url')->where($condition)->order('sort')->select();
            // dump(M()->getlastsql());
            return $data;
        }

        public function getPrice($id) {
            $Price = M('Price');
            $condition = array();
            $condition['house_id'] = $id;
            $condition['start_day'] = 0;
            $condition['end_day'] = 0;
            $default = $Price ->field('price')->where($condition)->find();
            unset($condition['start_day']);
            $condition['end_day'] = array('neq',0);
            $more = $Price->where($condition)->field('start_day,end_day,price')->order('start_day')->select();
            return array('default'=>$default['price'],'more'=>$more);
        }

          /**
     * 计算租房的总价格，注意酒店一天以本日中午12：00到次日中午12：00为一天 .post方法
     * @param <type> $house_id 房型ID(暂只支持单个房型)TODO
     * @param <type> $amount （预订相应房型的房间数量）
     * @param <type> $start_time 入住时间
     * @param <type> $end_time  离开时间
     */
    public function calPrice(){
        $start_time = strtotime($_POST['start_time']);
        $end_time = strtotime( $_POST['end_time'] );
        $amount = intval( $_POST['amount'] );
        $house_id = intval( $_POST['house_id'] );
        //停留时间
        $stayDay = ceil ( ($end_time - $start_time)/(60*60*24) );//向下取一位
        //$end_hour = date('h',$end_time);
        $realPrice = $this->getRealPrice($house_id, $stayDay);
        $totalPrice = $realPrice*$stayDay*$amount;

        echo $totalPrice;
        //echo array($realPrice,$stayDay,$totalPrice);
    }

     public function getTotalPrice($house_id,$amount,$start_time,$end_time){
        $start_time = strtotime($start_time);
        $end_time = strtotime($end_time );
        $amount = intval( $amount );
        $house_id = intval( $house_id );
        //停留时间
        $stayDay = ceil ( ($end_time - $start_time)/(60*60*24) );//向下取一位
        //$end_hour = date('h',$end_time);
        $realPrice = $this->getRealPrice($house_id, $stayDay);
        $totalPrice = $realPrice*$stayDay*$amount;
        return $totalPrice;
        //echo array($realPrice,$stayDay,$totalPrice);
    }
        /**
     *根据入住停留时间获取每天的房价
     * @param <type> $house_id 房型
     * @param <type> $stayDay 租房的天数
     * @return <type>
     */
    public function getRealPrice($house_id,$stayDay){
        $house_id = intval($house_id);
        $stayDay = intval($stayDay);
        $cond = array();
        if($stayDay > 0){
            $cond['start_day'] = array('elt',$stayDay);
            $cond['end_day'] = array('egt',$stayDay);
            $cond['house_id'] = $house_id;
            $price = M('Price')->where($cond)->order('start_day asc')->find();
            if(is_null($price)){
                unset($cond['end_day']);
                $cond['start_day'] = $cond['end_day'] = 0 ;
                $price = M('Price')->where($cond)->order('start_day asc')->find();//default price
            }
            $realPrice = $price['price'];
            return $realPrice;
        }
    }
    
}
?>
